package kordegi.forumsystem.shiro;

import io.github.yidasanqian.json.JsonUtil;
import io.jsonwebtoken.Claims;
import kordegi.forumsystem.common.lang.Result;
import kordegi.forumsystem.util.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author kordegi
 * @date 2022.05.04 20:39
 * @Description
 */

@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    JwtUtils jwtUtils;

    /**
     * @Description 获取 token
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");
        if (StringUtils.isEmpty(jwt)) return null;

        return new JwtToken(jwt);
    }

    /**
     * @Description 处理登录异常，装入Result
     * @Mentioning 用到了 json-util 和 fastjson
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        try {
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            Result r = Result.fail(throwable.getMessage());
            String json = JsonUtil.toJsonString(r);
            httpServletResponse.getWriter().println(json);
        } catch (IOException ex) {
        }

        return false;
    }

    /**
     * @Description 拦截校验, 对头部有 Authorization 进行校验 jwt 有效性，没问题直接 executeLogin
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("Authorization");

        //是否权限判断
        if (StringUtils.isEmpty(token)) return true;
        else {
            Claims claim = jwtUtils.getClaimsByToken(token);
            if (claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) throw new ExpiredCredentialsException("token失效，请重新登录");
        }

        //自动登录
        return executeLogin(servletRequest, servletResponse);
    }


    /**
     * @Description preHandle是拦截器的前置拦截； 表示对跨域的支持
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        //webUtil起到转换对象的作用
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);

        //和前端协调返回
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-control-Allow-Methods", "GET, POST, PUT, DELETE");
        httpServletResponse.setHeader("Access-control-Allow-Headers", "*");//httpServletRequest.getHeader("Access-control-Allow-RequestHeader")

        //跨域时先发一个OPTIONS，给OPTIONS返回正常状态并且让后面的拦截器失效
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }
}
